// Common DiagInfo Script for creating Fixposition and Ghost Diagnosis Information

// selector: ID of container elementFromPoint
// type: "fixpos" or "ghost", only changes the tag and translation prefix

function aptDiagInfo(selector, type) {
    // Variable declaration
    var tagName;
    var prefix;
    switch (type) {
        case "ghost":
            tagName = sessionStorage.getItem("apt_PLC.OpcTopic") + sessionStorage.getItem("apt_PLC.Tags.Ghost.DiagInfo");
            prefix = "T02_UserGuide_Ghost";
            break;
        case "fixpos":
            tagName = sessionStorage.getItem("apt_PLC.OpcTopic") + sessionStorage.getItem("apt_PLC.Tags.FixPosDiagInfo");
            prefix = "T02_UserGuide_FixPos";
            break;
        default:
            throw "[APT Error]: Type of diag info is unknown. Please check the status win .json file for 'AddGhostDiagInfo' property 'type'";
    }

    var diagId = getElementGlobalID();
    var diagWrapperId = getElementGlobalID();
    var advisedTagId;
    var advisedTextId;

    function createDom() {
        var content = "<div class='GhostModeDiagInfoWrapper hide' id='" + diagWrapperId + "'><span class ='GhostModeDiagInfo' id='" + diagId + "'></span></div>";
        $('#' + selector).append(content);
    }

    function dataHandler() {
        advisedTagId = emosWS.advise(tagName, function(msg) {
            if (msg.value == 0) {
                $('#' + diagWrapperId).addClass("hide");
            } else {
                var filler = "";
                if (parseInt(msg.value) < 9) filler = "0";

                advisedTextId = emosWS.sendAdviseText(prefix + filler + msg.value, "name", function(txt) {
                    if (txt.hasOwnProperty("value") && txt.value != "") {
                        $('#' + diagId).text(txt.value);
                        $('#' + diagWrapperId).removeClass("hide");
                    } else {
                        $('#' + diagWrapperId).addClass("hide");
                    }
                }).getId();
            }
        }).getId();
    }

    function eventHandler() {
        $('#' + diagId).on('remove', function() {
            emosWS.unadvise(advisedTagId); // Unadvise Diag tag
            emosWS.unadvise(advisedTextId); // Unadvise Text from db
        });
    }

    createDom();
    dataHandler();
    eventHandler();
}
